package com.cxd.app.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cxd.app.entity.base.WithdrawCashBase;
import com.cxd.base.common.constants.UserConstants;
import com.cxd.base.mapper.read.RManageMapper;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.WithdrawalUtil;
import com.cxd.base.util.date.DateUtil;

/**
 * <一句话功能简述> <功能详细描述>
 * @author wtj
 * @date 2015年12月11日 下午3:31:29
 * @company CXD
 * @version [Copyright (c) 2015 V001]
 */
@Service("withdrawCashService")
public class WithdrawCashService {
	@Resource
	FeeConfigService feeConfigService;
	
	@Resource
	RManageMapper rmanageMapper;
	
	@Resource
	public BeanTools bt;
	public double calculateFee(double amount,String withdrawType) {
//		return feeConfigService.getFee(FeePoint.WITHDRAW, FeeType.FACTORAGE, null,
//				null, amount);
		return Double.parseDouble(WithdrawalUtil.getWithdrawalFee(withdrawType,amount).getFee());
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void applyWithdrawCash(WithdrawCashBase withdraw){
		// FIXME:缺验证
//		withdraw.setFee(calculateFee(withdraw.getMoney()));
		withdraw.setCashFine(0D);

		withdraw.setId(generateId());
		withdraw.setTime(new Date());
		withdraw.setStatus(UserConstants.WithdrawStatus.WAIT_VERIFY);
		bt.add(withdraw);
	}
	
	/**
	 * 生成充值id
	 * 
	 * @return
	 */
	private synchronized  String generateId() {
		String gid = DateUtil.dateToString(new Date(), "yyyyMMdd");
		
		Map<String,Object> root = new HashMap<String,Object>();
		root.put("tableName", "WITHDRAW_CASH");
		root.put("likeId", gid + "%");
		Map<String,Object> map = rmanageMapper.loadLastId(root);
		// String hql = "select withdraw from WithdrawCash withdraw where withdraw.id = (select max(withdrawM.id) from WithdrawCash withdrawM where withdrawM.id like ?)";
		Integer itemp = 0;
		if(map!=null){
			String temp = map.get("ID").toString();
			temp = temp.substring(temp.length() - 6);
			itemp = Integer.valueOf(temp);
		}
		itemp++;
		gid += String.format("%08d", itemp);
		return gid;
	}
}
